

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:flutter_swipe_action_cell/core/cell.dart';
import 'package:get/get.dart';
import 'package:smart_freezer/core/model/product_model.dart';
import 'package:smart_freezer/core/resources/app_config.dart';
import 'package:smart_freezer/core/resources/icon_names.dart';
import 'package:smart_freezer/core/resources/routers.dart';
import 'package:smart_freezer/core/service/api/app_api.dart';
import 'package:smart_freezer/core/service/service/result_data.dart';
import 'package:smart_freezer/core/utils/local_storage.dart';
import 'package:smart_freezer/core/utils/logs.dart';
import 'package:smart_freezer/core/utils/tr_extension.dart';
import 'package:smart_freezer/generated/locale_keys.g.dart';

class SettingCollectDevice extends StatefulWidget {
  const SettingCollectDevice({Key? key}) : super(key: key);

  @override
  State<SettingCollectDevice> createState() => _SettingCollectDeviceState();
}

class _SettingCollectDeviceState extends State<SettingCollectDevice> {

  List<ProductModel> _productList = [];
  int currentPage = 0;

  var searchTextController = TextEditingController();
  FocusNode _searchFocusNode = FocusNode();

  bool isAllCheck = false;

  var isDarkMode = LocalStorage.getThemeMode() == 1;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // backgroundColor: Colors.white,
        elevation: 0,
        leadingWidth: 50,
        leading: InkWell(
          onTap: () {
            Get.back();
          },
          child: Container(
            padding: EdgeInsets.fromLTRB(0, 9, 0, 9),
            child: Icon(Icons.arrow_back_ios_rounded),
          ),
        ),
        title: Text(LocaleKeys.set_up_collect.trc(), ),
        centerTitle: true,
      ),
      body: Container(
        width: MainCommon.screenWidth,
        // color: Colors.white,
        child: Column(
          children: [
            Container(height: 20, color: isDarkMode ? Colors.black : Color(0xFFF1F3F8),),
            // 设备列表
            Expanded(
              child: EasyRefresh.custom(
                  header: MaterialHeader(valueColor: AlwaysStoppedAnimation(isDarkMode ? Colors.white : Colors.black)),
                  footer: MaterialFooter(valueColor: AlwaysStoppedAnimation(isDarkMode ? Colors.white : Colors.black)),
                  firstRefresh: true,
                  emptyWidget: _productList.isEmpty ? Center(
                    child: Column(
                      children: [
                        SizedBox(height: 50,),
                        Image.asset(IconNames.home_w06, width: MainCommon.screenWidth * 0.6,),
                        Text(LocaleKeys.other_no_data.trc(), style: TextStyle(color: Colors.grey),),
                      ],
                    ),
                  ) : null,
                  slivers: [
                    SliverList(
                      delegate: SliverChildBuilderDelegate(
                              (context, index) {

                                final productModel = _productList[index];

                                // 温度过高
                                bool isNotNormal = productModel.highTemperature.isNotEmpty || productModel.lowerTemperature.isNotEmpty ||
                                                   productModel.t1Failure.isNotEmpty || productModel.t2Failure.isNotEmpty || productModel.t3Failure.isNotEmpty ||
                                                   productModel.condenserClean.isNotEmpty || productModel.doorOpen.isNotEmpty;
                                bool isMoreHigh = productModel.highTemperature.isNotEmpty;   // false

                            return SwipeActionCell(
                              key: ObjectKey(productModel),
                              index: index,
                              trailingActions: <SwipeAction>[
                                SwipeAction(
                                    widthSpace: 50, // 暂时隐藏
                                    icon: Icon(Icons.delete_forever, color: Colors.white,),
                                    onTap: (CompletionHandler handler) async {
                                      final model = _productList[index];
                                      logs("model.collectId: ${model.collectId}");
                                      _deleteCollect(model.collectId);
                                    },
                                    // color: Colors.transparent
                                ),
                              ],
                              child: Container(
                                color: isDarkMode ? MainCommon.darkBlueMaterialColor : Colors.white,
                                child: Column(
                                  children: [
                                    Container(
                                      padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
                                      child: Row(
                                        children: [
                                          // Icon(productModel.isSelected ? Icons.radio_button_unchecked : Icons.radio_button_checked),
                                          Container(
                                            width: 20,
                                            child: Checkbox(
                                              value: productModel.isSelected,
                                              activeColor: Colors.blue,
                                              shape: CircleBorder(),
                                              onChanged: (bool? value) {
                                                setState(() {
                                                  var srcModel = productModel;
                                                  srcModel.isSelected = !productModel.isSelected;
                                                  final index = _productList.indexOf(productModel);
                                                  _productList.replaceRange(index, index + 1, [srcModel]);
                                                });

                                                // 判断是否全为true/false
                                                final tempTrueList = _productList.where((element) => element.isSelected == true).toList();
                                                final tempFalseList = _productList.where((element) => element.isSelected == false).toList();
                                                isAllCheck = tempTrueList.length == _productList.length ? true : isAllCheck;
                                                isAllCheck = tempFalseList.length == _productList.length ? false : isAllCheck;
                                                //
                                                // widget.selectValue([model]);
                                              },
                                            ),
                                          ),


                                          // 冰柜背景
                                          Stack(
                                            alignment: Alignment.center,
                                            children: [
                                              Image.asset(IconNames.home_xzbg, width: 70,),
                                              Positioned(
                                                  child: Container(
                                                    width: 70,
                                                    child: CachedNetworkImage(
                                                      fit: BoxFit.fitWidth,
                                                      placeholder: (ctx, url) => Image.asset(IconNames.home_sb_a, fit: BoxFit.fill, width: 70),
                                                      imageUrl: productModel.icon,
                                                      errorWidget: (ctx, url, _) => Image.asset(IconNames.home_sb_a, fit: BoxFit.fill, width: 70 ),
                                                    ),
                                                    // Image.asset(IconNames.home_sb_a, width: 70,),
                                                  )
                                              )

                                            ],
                                          ),

                                          SizedBox(width: 5,),
                                          // 第二列
                                          Column(
                                            crossAxisAlignment: CrossAxisAlignment.start,
                                            children: [
                                              Container(
                                                  child: Text("${productModel.code} ${productModel.modelName} ${productModel.name}", style: TextStyle(fontWeight: FontWeight.bold),),
                                                constraints: BoxConstraints(
                                                  maxWidth: 230,
                                                ),

                                              ),

                                              Container(
                                                width: MainCommon.screenWidth - 130,
                                                child: Row(
                                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                                  children: [
                                                    Row(
                                                      children: [
                                                        CircleAvatar(
                                                          backgroundColor: productModel.networkStatus == 1 ? Colors.green : Colors.grey,
                                                          radius: 4,
                                                        ),
                                                        SizedBox(width: 5,),
                                                        Text("T1: ${productModel.temperatureOne}℃", style: TextStyle(color: Colors.grey),)
                                                      ],
                                                    ),

                                                    Container(
                                                      decoration: BoxDecoration(
                                                        color: productModel.networkStatus == 1 ? (isNotNormal ? Colors.red.shade50 : Colors.green.shade50) : Colors.grey.shade200,
                                                        borderRadius: BorderRadius.circular(5),
                                                      ),
                                                      padding: EdgeInsets.fromLTRB(5, 2, 5, 3),
                                                      constraints: BoxConstraints(
                                                        maxWidth: productModel.networkStatus == 1 ? (isNotNormal ? MainCommon.screenWidth * 0.3 : double.infinity) : double.infinity,
                                                      ),
                                                      alignment: Alignment.center,
                                                      child: Text("${productModel.networkStatus == 1 ? productModel.warningMessage
                                                          : LocaleKeys.other_lixian.trc()}",
                                                        style: TextStyle(color: productModel.networkStatus == 1 ? (isNotNormal ? Colors.red : Colors.green) : Colors.grey, fontSize: 12,), maxLines: 1, overflow: TextOverflow.ellipsis,),
                                                    ),

                                                  ],
                                                ),
                                              ),

                                              // 地点
                                              Row(
                                                crossAxisAlignment: CrossAxisAlignment.end,
                                                children: [
                                                  Image.asset(IconNames.home_positioning, height: 20,),
                                                  Text("${productModel.hallName} ${productModel.floorName}", style: TextStyle(color: Colors.grey),),
                                                ],
                                              ),
                                            ],
                                          ),
                                        ],
                                      ),
                                    ),

                                    Divider(
                                      height: 1,
                                      thickness: 0,
                                      indent: 0,
                                      endIndent: 0,
                                      // color: Color(0xFFD9D9D9),
                                    ),
                                  ],
                                ),
                              ),
                            );
                          },
                        childCount: _productList.length
                      ),
                    ),
                  ],
                onRefresh: () async {
                    _getNewList();
                },
                onLoad: () async {
                    _getMoreList();
                },
              ),
            ),

            // Container(height: 10, color: Color(0xFFF1F3F8),),
            // 加入收藏/批量控制
            Container(
              color: isDarkMode ? MainCommon.darkBlueMaterialColor : Colors.white, //Colors.white,
              padding: EdgeInsets.fromLTRB(0, 10, 0, 10),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  Row(
                    children: [
                      Container(
                        width: 20,
                        child: Checkbox(
                          value: isAllCheck,
                          activeColor: Colors.blue,
                          shape: CircleBorder(),
                          onChanged: (bool? value) {
                            setState(() {
                              isAllCheck = !isAllCheck;

                              // 全选
                              _productList = _productList.map((e) {
                                var srcModel = e;
                                srcModel.isSelected = isAllCheck;
                                return srcModel;
                              }).toList();
                            });


                          },
                        ),
                      ),
                      Text(LocaleKeys.set_up_all.trc()),
                    ],
                  ),

                  Row(
                    children: [
                      InkWell(
                        onTap: (){
                          List<String> _productIdList = [];
                          _productList.forEach((element) {
                            if(element.isSelected) {
                              _productIdList.add(element.id);
                            }
                          });

                          if(_productIdList.isNotEmpty){
                            Get.toNamed(LCRouter.device_setting, arguments: _productIdList);
                          }

                        },
                        child: Container(
                          height: 44,
                          decoration: BoxDecoration(
                            color: Color(0xFF234485),
                            borderRadius: BorderRadius.circular(22),
                          ),
                          alignment: Alignment.center,
                          padding: EdgeInsets.fromLTRB(40, 0, 40, 0),
                          child: Text(LocaleKeys.set_up_control_select.trc(), style: TextStyle(color: Colors.white, fontSize: 16),),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),

          ],
        ),
      ),
    );
  }

  _getNewList() {
    _productList = [];
    currentPage = 1;
    _getCollectList(currentPage);
  }
  _getMoreList() {
    currentPage += 1;
    _getCollectList(currentPage);
  }

  // 获取设备列表
  _getCollectList(int page) async {
    final params = {"page": "$page", "limit": "20"};
    ResultData data = await AppApi.getInstance().getCollectList(params);
    if(data.code == 0){
      final list = data.data as List;
      if(list.isEmpty) return;

      final modelList = list.map((e) => ProductModel.fromJson(e)).toList();
      if(currentPage == 1) {
        _productList = modelList;
      }else{
        _productList.addAll(modelList);
      }

      setState(() {});

      _productList.forEach((element) async {
        final params = {"productId": "${element.id}"};
        final index = _productList.indexOf(element);
        ResultData data = await AppApi.getInstance().getProductInfo(params);
        if(data.code == 0){
          final productModel = ProductModel.fromJson(data.data);
          productModel.collectId = element.collectId;
          _productList[index] = productModel;
          if(index == _productList.length - 1){
            setState((){});
          }
        }
      });

    }else {
      SmartDialog.showToast(data.msg);
    }
  }

  // 删除收藏
  _deleteCollect(String collectId) async {
    final params = {"collectId": collectId};
    ResultData data = await AppApi.getInstance().removeCollectList(params);
    if(data.code == 0){
      _getNewList();
    }else {
      SmartDialog.showToast(data.msg);
    }
  }

  // 批量控制


}
